"""
主窗口UI类
重构后的主窗口，使用模块化组件
"""

import subprocess
import platform
from pathlib import Path

try:
    import tomllib  # Python 3.11+
except ImportError:
    import tomli as tomllib  # Python 3.10及以下

from PySide6.QtWidgets import (QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, 
                              QSplitter, QMessageBox)
from PySide6.QtCore import Qt

from ..config.settings import AppConfig
from ..core.color_block_generator import ColorBlockGenerator
from ..utils.color_utils import ColorUtils
from ..utils.file_utils import FileUtils
from .widgets import ControlPanel, PreviewPanel, InfoPanel
from .utils import UIUtils


class MainWindow(QMainWindow):
    """重构后的主窗口类"""
    
    def __init__(self):
        super().__init__()
        self.generator = ColorBlockGenerator()
        self.current_color = AppConfig.DEFAULT_COLOR
        self.project_info = self._load_project_info()
        
        self._setup_ui()
        self._connect_signals()
        self._update_preview()
    
    def _load_project_info(self):
        """从pyproject.toml加载项目信息"""
        project_root = Path(__file__).parent.parent.parent
        pyproject_path = project_root / "pyproject.toml"
        
        with open(pyproject_path, 'rb') as f:
            config = tomllib.load(f)
            
        project = config['project']
        return {
            'name': project['description'] or project['name'],
            'version': project['version']
        }
    
    def _setup_ui(self):
        """设置UI界面"""
        self.setWindowTitle(self.project_info['name'])
        self.setMinimumSize(AppConfig.WINDOW_MIN_WIDTH, AppConfig.WINDOW_MIN_HEIGHT)
        self.resize(AppConfig.WINDOW_WIDTH, AppConfig.WINDOW_HEIGHT)
        
        # 设置窗口图标（根据操作系统选择对应格式）
        icons_dir = Path(__file__).parent.parent.parent / "resources" / "icons"
        
        system = platform.system().lower()
        if system == "windows":
            icon_file = "app-icon.ico"
        elif system == "darwin":  # macOS
            icon_file = "app-icon.icns"
        else:  # Linux和其他系统
            icon_file = "app-icon.png"
        
        icon_path = icons_dir / icon_file
        if icon_path.exists():
            from PySide6.QtGui import QIcon
            self.setWindowIcon(QIcon(str(icon_path)))
        
        # 创建中央部件
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        # 主布局
        main_layout = QHBoxLayout(central_widget)
        
        # 创建分割器
        splitter = QSplitter(Qt.Horizontal)
        main_layout.addWidget(splitter)
        
        # 右侧面板容器
        right_panel = QWidget()
        right_layout = QVBoxLayout(right_panel)
        right_layout.setContentsMargins(0, 0, 0, 0)
        
        # 创建组件
        self.control_panel = ControlPanel()
        self.preview_panel = PreviewPanel()
        self.info_panel = InfoPanel()
        
        # 添加到右侧面板
        right_layout.addWidget(self.preview_panel)
        right_layout.addWidget(self.info_panel)
        
        # 添加到分割器
        splitter.addWidget(self.control_panel)
        splitter.addWidget(right_panel)
        
        # 设置分割器比例
        splitter.setStretchFactor(0, 1)
        splitter.setStretchFactor(1, 1)
    
    def _connect_signals(self):
        """连接信号和槽"""
        # 控制面板信号
        self.control_panel.color_changed.connect(self._on_color_changed)
        self.control_panel.size_changed.connect(self._on_size_changed)
        self.control_panel.download_requested.connect(self._download_image)
        
        # 预览面板信号
        self.preview_panel.color_changed.connect(self._on_preview_color_changed)
        
        # 打开目录按钮
        self.control_panel.open_dir_btn.clicked.connect(self._open_directory)
    
    def _on_color_changed(self, color_text: str):
        """颜色输入改变"""
        try:
            if ColorUtils.validate_hex_color(color_text):
                self.current_color = ColorUtils.normalize_hex_color(color_text)
                # 同步更新预览面板的颜色选择器
                self.preview_panel.set_color(self.current_color)
                self._update_preview()
        except:
            pass
    
    def _on_size_changed(self, width: int, height: int):
        """尺寸改变"""
        # 尺寸改变时也可以更新预览
        self._update_preview()
    
    def _on_preview_color_changed(self, hex_color: str):
        """预览面板颜色改变"""
        self.current_color = hex_color
        # 同步更新控制面板的颜色输入
        self.control_panel.set_color(hex_color)
        self._update_preview()
    
    def _update_preview(self):
        """更新预览"""
        try:
            # 获取当前尺寸
            width, height = self.control_panel.get_size()
            
            # 生成预览图片
            preview_image = self.generator.generate_preview(
                self.current_color, 
                AppConfig.PREVIEW_SIZE
            )
            
            # 获取RGB值
            rgb = ColorUtils.hex_to_rgb(self.current_color)
            
            # 更新预览面板
            self.preview_panel.update_preview(preview_image, self.current_color, rgb)
            
        except Exception as e:
            self.preview_panel.clear_preview()
            UIUtils.show_error(f"预览更新失败: {str(e)}", self)
    
    def _open_directory(self):
        """打开目录"""
        directory = self.control_panel.get_save_directory()
        UIUtils.open_directory(directory)
    
    def _download_image(self):
        """下载图片"""
        # 获取参数
        hex_color = self.current_color
        width, height = self.control_panel.get_size()
        format_name = self.control_panel.get_format_name()
        save_dir = self.control_panel.get_save_directory()
        
        # 验证参数
        if not ColorUtils.validate_hex_color(hex_color):
            UIUtils.show_warning(AppConfig.ERROR_MESSAGES["INVALID_COLOR"], self)
            return
        
        if width <= 0 or height <= 0:
            UIUtils.show_warning(AppConfig.ERROR_MESSAGES["INVALID_SIZE"], self)
            return
        
        if not save_dir:
            UIUtils.show_warning("请选择保存目录", self)
            return
        
        # 获取自定义文件名或使用默认命名
        custom_filename = self.control_panel.get_custom_filename()
        if custom_filename:
            # 使用自定义文件名，确保添加正确的扩展名
            extension = FileUtils.get_file_extension(format_name)
            if not custom_filename.lower().endswith(extension.lower()):
                filename = custom_filename + extension
            else:
                filename = custom_filename
        else:
            # 使用默认命名
            filename = f"color_{hex_color.lstrip('#')}_{width}x{height}"
            extension = FileUtils.get_file_extension(format_name)
            filename += extension
        
        # 确保文件名安全且唯一
        filename = FileUtils.get_safe_filename(filename)
        filename = FileUtils.get_unique_filename(save_dir, filename)
        filepath = str(Path(save_dir) / filename)
        
        # 执行下载
        try:
            success = self.generator.generate_and_save(
                hex_color, width, height, filepath, format_name
            )
            
            if success:
                message = f"{AppConfig.SUCCESS_MESSAGES['DOWNLOAD_SUCCESS']}\n保存路径: {filepath}"
                UIUtils.show_info(message, self)
            else:
                UIUtils.show_error(AppConfig.ERROR_MESSAGES["SAVE_ERROR"], self)
                
        except Exception as e:
            UIUtils.show_error(f"{AppConfig.ERROR_MESSAGES['SAVE_ERROR']}\n{str(e)}", self)